package hydrap2p.modulemanager.listen;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import hydrap2p.ServiceLocation;
import hydrap2p.modulemanager.ModuleInfo;
import hydrap2p.modulemanager.ModuleListener;

public class ThriftListener implements Listener {

	private ServiceLocation location;
	private ModuleListener.Iface listener;
	
	public ThriftListener(ServiceLocation listenerloc)
	{
		this.location=listenerloc;
	}
	
	public void connect() throws TException
	{
		TTransport transport = new TSocket(location.address,location.port);
		transport.open();
		listener=new ModuleListener.Client(new TBinaryProtocol(transport));
		if (!listener.supportedInterfaces().contains("ModuleListener"))
			throw new TException("Invalid Listener, missing ModuleListener");
	}
	
	@Override
	public void addModule(ModuleInfo module) throws Exception {
		listener.addModule(module);
	}

	@Override
	public void updateModule(ModuleInfo module) throws TException {
		listener.updateModule(module);
	}

	@Override
	public void delModule(ModuleInfo module) throws TException {
		listener.delModule(module);
	}

	@Override
	public void stop() {
		// Do nothing
	}


	@Override
	public int hashCode()
	{
		return location.hashCode();
	}
	
	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof ThriftListener)
		{
			ThriftListener other = (ThriftListener) obj;
			return other.location.equals(this.location);
		}
		return false;
	}
	
	@Override
	public String toString()
	{
		return "ModuleListener at "+location;
	}
}
